package com.smfx.yxt.wechat.hander;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.enums.FileType;
import com.smfx.yxt.common.enums.RelationType;
import com.smfx.yxt.model.AttachmentList;
import com.smfx.yxt.model.StudentInfo;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.reqVo.ParentReqVO;
import com.smfx.yxt.service.IAttachmentListService;
import com.smfx.yxt.service.IClassAlbumService;
import com.smfx.yxt.service.IParentService;
import com.smfx.yxt.service.IStudentService;
import com.smfx.yxt.service.ITeacherService;
import com.smfx.yxt.utils.DateUtil;
import com.smfx.yxt.utils.FileUtils;
import com.smfx.yxt.utils.PropertiesUtil;
import com.smfx.yxt.utils.TextUtil;
import com.smfx.yxt.view.ParentRelStudentView;
import com.smfx.yxt.wechat.message.ArticleItem;
import com.smfx.yxt.wechat.message.InputMessage;
import com.smfx.yxt.wechat.message.OutputMessage;
import com.smfx.yxt.wechat.message.WechatEwm;
import com.smfx.yxt.wechat.model.WechatUserInfo;
import com.smfx.yxt.wechat.utils.FileUtil;
import com.smfx.yxt.wechat.utils.MessageUtil;
import com.smfx.yxt.wechat.utils.WechatUtils;

@Component
public class WechatHander {
	
	@Autowired
	private IParentService parentService;
	@Autowired
	private IStudentService studentService;
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private IAttachmentListService attachmentListService;
	@Autowired
	private IClassAlbumService classAlbumService;
	
	public OutputMessage respMessage(InputMessage inputMsg) throws Exception{
		String servername = inputMsg.getToUserName();// 服务端  
        String custermname = inputMsg.getFromUserName();// 客户端  
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间  
        
        // 取得消息类型  
        String msgType = inputMsg.getMsgType();  
        OutputMessage outputMsg = new OutputMessage();  
        outputMsg.setFromUserName(servername);  
        outputMsg.setToUserName(custermname);  
        outputMsg.setCreateTime(returnTime);  
        String respContent = null;
        // 根据消息类型获取对应的消息内容  
        if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
        	insertWechatReceiveMessage(outputMsg, inputMsg);
        } // 获取并返回多图片消息  
        else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
        	insertWechatReceiveMessage(outputMsg, inputMsg);
        }// 视频消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_SHORTVIDEO) || msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
			insertWechatReceiveMessage(outputMsg, inputMsg);
		}
		else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {// 语音消息
			
		}// 地理位置消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
			
		}// 链接消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
			
		}
		else {
    		// 事件推送
    		if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
    			// 事件类型
    			String eventType = inputMsg.getEvent();
    			// 关注
    			if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
    				List<ArticleItem> newsList = new ArrayList<>();
	    			ArticleItem item = new ArticleItem();
	    	        item.setTitle("欢迎关注石门附小云校通");
	    	        item.setDescription("石门附小基于“互联网+”背景下的优质发展，实现移动化办公、移动化学校管理、家校e互动，提供云计算、大数据、物联网的教育教学服务。");
	    	        item.setPicUrl("http://yxt.nhedu.net/file/smfx.jpg");
	    	        item.setUrl( "https://mp.weixin.qq.com/s/UyUcVf2XvXlwbyW8zsFIiw");
	    	        newsList.add(item);
    				outputMsg.setArticleCount(newsList.size());
    				outputMsg.setArticles(newsList);
    				outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
    			}
    			// 取消关注
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
    				// TODO 取消订阅后用户不会再收到公众账号发送的消息，因此不需要回复
    			}
    			// 扫描带参数二维码
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
    				String eventKey = inputMsg.getEventKey();
    				eventTypeScanOutPut(outputMsg, eventKey, inputMsg.getFromUserName());
    			}
    			// 上报地理位置
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
    				// TODO 处理上报地理位置事件
    			}
    			// 自定义菜单
    			else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
//    				eventTypeClick(outputMsg, inputMsg);
    			}
    		}else {
    			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                outputMsg.setContent(respContent);
    		}
		}
        return outputMsg;
	}
	
	private void insertWechatReceiveMessage(OutputMessage outputMsg, 
			InputMessage inputMsg) {
		boolean isOk = false;
    	if(!isOk) {
    		outputMsg.setContent("欢迎访问石门附小云校通公众号");
    	}
    	outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
	}

	/**
	 * 扫描带参数二维码响应
	 * @auther 胡启萌
	 * @Date 2016年12月4日
	 * @param outputMsg
	 * @param eventKey
	 * @param openid
	 */
	private void eventTypeScanOutPut(OutputMessage outputMsg, String eventKey, String openid) {
		if(eventKey.startsWith(WechatEwm.INVITE_BIND_STU_EWM.getCode())) {
			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			String key = eventKey.substring(WechatEwm.INVITE_BIND_STU_EWM.getCode().length(), eventKey.length());
			Integer studentId = Integer.valueOf(key);
			ParentReqVO vo = new ParentReqVO();
			vo.setOpenid(openid);
			vo.setStudentId(studentId);
			int count = parentService.selectStudentCountForParent(vo);
			StudentInfo student = studentService.selectById(studentId);
			String reqUrl = Const.BASEPATH + Const.STUDENT_ROLE + "?sid=" + studentId;
			if(count == 0) {
				vo.setOpenid(null);
				ParentRelStudentView view = new ParentRelStudentView();
				view.setOpenid(openid);
				view.setStudentId(studentId);
				WechatUserInfo userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(), openid);
				String headImgUrl = FileUtils.writeHttpFile(userInfo.getHeadimgurl(), RelationType.HEAD_IMG_URL.getCode());
				view.setHeadImgUrl(headImgUrl);
				view.setName(userInfo.getNickname());
				parentService.saveParentRelStudent(view);
				String content = PropertiesUtil.getProperty("parent_bind_success");
				content = TextUtil.format(content,new String[]{
						student.getSchoolName(), 
						student.getName(), 
						DateUtil.dateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT2),
						reqUrl});
				outputMsg.setContent(content);
			}else {
				String content = PropertiesUtil.getProperty("parent_had_bind");
				content = TextUtil.format(content,new String[]{
						student.getName(), 
						student.getSchoolName(), 
						reqUrl});
				outputMsg.setContent(content);
			}
		}else if(eventKey.startsWith(WechatEwm.INVITE_BIND_TEA_WEM.getCode())) {
			outputMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			String key = eventKey.substring(WechatEwm.INVITE_BIND_TEA_WEM.getCode().length(), eventKey.length());
			Integer teacherId = Integer.valueOf(key);
			TeacherInfo teacher = teacherService.selectById(teacherId);
			if(StringUtils.isNotBlank(teacher.getOpenid2())) {
				String content = PropertiesUtil.getProperty("teacher_had_bind");
				content = TextUtil.format(content,new String[]{
						teacher.getSchoolName(), 
						teacher.getName()});
				outputMsg.setContent(content);
			}else {
				WechatUserInfo userInfo = WechatUtils.getUserInfo(WechatUtils.getWechatModel().getAccessToken(), openid);
				String headImgUrl = FileUtils.writeHttpFile(userInfo.getHeadimgurl(), RelationType.HEAD_IMG_URL.getCode());
				teacher.setHeadImgUrl(headImgUrl);
				teacher.setOpenid2(userInfo.getOpenid());
				teacherService.updateById(teacher);
				String content = PropertiesUtil.getProperty("teacher_bind_success");
				content = TextUtil.format(content,new String[]{
						teacher.getSchoolName(), 
						teacher.getName(), 
						DateUtil.dateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT2)});
				outputMsg.setContent(content);
			}
		}
	}

	
	class WechatMsgExecutor implements Runnable {
		
		private InputMessage inputMsg;
		
		private AttachmentList attachment;
		
		public WechatMsgExecutor(InputMessage inputMsg, AttachmentList attachment) {
			this.inputMsg = inputMsg;
			this.attachment = attachment;
		}

		@Override
		public void run() {
			try { 
				String fileType = inputMsg.getMsgType();
    			if(FileType.IMAGE.getCode().equals(fileType) || 
    					FileType.VIDEO.getCode().equals(fileType) ||
    					FileType.SHORTVIDEO.getCode().equals(fileType) ||
    					FileType.VOICE.getCode().equals(fileType)) {
    				String path = FileUtil.downloadWechatFile(inputMsg, RelationType.CLASS_ALBUM.getCode(), false);
    				attachment.setAttachmentUrl(path);
    				if(FileType.VIDEO.getCode().equals(fileType) || 
    						FileType.SHORTVIDEO.getCode().equals(fileType)) {
    					String picUrl = FileUtil.downloadWechatFile(inputMsg, RelationType.CLASS_ALBUM.getCode(), true);
    					attachment.setAttachmentExtUrl(picUrl);
    				}
    			}
    			attachmentListService.insertSelective(attachment);
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}
}
